from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QPushButton,
                               QTableWidget, QTableWidgetItem, QDialog, QLabel,
                               QLineEdit, QMessageBox, QComboBox)
from PySide6.QtCore import Qt
import hashlib
from utils.db import db


class StaffDialog(QDialog):
    def __init__(self, parent=None, staff_data=None):
        super().__init__(parent)
        self.staff_data = staff_data
        self.setup_ui()
        if staff_data:
            self.load_staff_data()

    def setup_ui(self):
        self.setWindowTitle("员工信息")
        self.setMinimumWidth(400)

        layout = QVBoxLayout(self)
        layout.setSpacing(15)

        # 用户名
        self.username_input = QLineEdit()
        self.username_input.setPlaceholderText("请输入用户名")
        layout.addWidget(QLabel("用户名:"))
        layout.addWidget(self.username_input)

        # 显示名称
        self.display_name_input = QLineEdit()
        self.display_name_input.setPlaceholderText("请输入显示名称")
        layout.addWidget(QLabel("显示名称:"))
        layout.addWidget(self.display_name_input)

        # 密码
        self.password_input = QLineEdit()
        self.password_input.setPlaceholderText("请输入密码")
        self.password_input.setEchoMode(QLineEdit.Password)
        layout.addWidget(QLabel("密码:"))
        layout.addWidget(self.password_input)

        # 确认密码
        self.confirm_password_input = QLineEdit()
        self.confirm_password_input.setPlaceholderText("请确认密码")
        self.confirm_password_input.setEchoMode(QLineEdit.Password)
        layout.addWidget(QLabel("确认密码:"))
        layout.addWidget(self.confirm_password_input)

        # 按钮
        button_layout = QHBoxLayout()
        self.save_btn = QPushButton("保存")
        self.cancel_btn = QPushButton("取消")

        self.save_btn.clicked.connect(self.save_staff)
        self.cancel_btn.clicked.connect(self.reject)

        button_layout.addWidget(self.save_btn)
        button_layout.addWidget(self.cancel_btn)

        layout.addLayout(button_layout)

    def load_staff_data(self):
        """加载员工数据"""
        self.username_input.setText(self.staff_data["username"])
        self.username_input.setReadOnly(True)  # 不允许修改用户名
        self.display_name_input.setText(self.staff_data["display_name"] or "")
        # 不显示密码，但允许修改

    def save_staff(self):
        """保存员工信息"""
        try:
            username = self.username_input.text().strip()
            display_name = self.display_name_input.text().strip()
            password = self.password_input.text()
            confirm_password = self.confirm_password_input.text()

            if not username:
                raise ValueError("用户名不能为空！")

            if not self.staff_data:  # 新建员工时密码必填
                if not password:
                    raise ValueError("密码不能为空！")

            if password != confirm_password:
                raise ValueError("两次输入的密码不一致！")

            if self.staff_data:  # 更新
                if password:  # 如果输入了新密码
                    hashed_password = hashlib.md5(password.encode()).hexdigest()
                    sql = """
                    UPDATE users 
                    SET display_name=?, password=?
                    WHERE id=?
                    """
                    db.execute(sql, (display_name, hashed_password, self.staff_data["id"]))
                else:  # 不修改密码
                    sql = """
                    UPDATE users 
                    SET display_name=?
                    WHERE id=?
                    """
                    db.execute(sql, (display_name, self.staff_data["id"]))
            else:  # 新建
                hashed_password = hashlib.md5(password.encode()).hexdigest()
                sql = """
                INSERT INTO users (username, password, display_name, role)
                VALUES (?, ?, ?, 'staff')
                """
                db.execute(sql, (username, hashed_password, display_name))

            self.accept()

        except Exception as e:
            QMessageBox.critical(self, "错误", str(e))


class StaffPage(QWidget):
    def __init__(self):
        super().__init__()
        self.setup_ui()
        self.load_staffs()

    def setup_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(20)

        # 工具栏
        toolbar = QHBoxLayout()
        self.add_btn = QPushButton("添加员工")
        self.refresh_btn = QPushButton("刷新")

        self.add_btn.setObjectName("primaryButton")
        self.refresh_btn.setObjectName("secondaryButton")

        self.add_btn.clicked.connect(self.add_staff)
        self.refresh_btn.clicked.connect(self.load_staffs)

        toolbar.addWidget(self.add_btn)
        toolbar.addWidget(self.refresh_btn)
        toolbar.addStretch()

        # 员工表格
        self.table = QTableWidget()
        self.table.setColumnCount(5)
        self.table.setHorizontalHeaderLabels([
            "ID", "用户名", "显示名称", "角色", "操作"
        ])

        # 设置表格样式
        self.table.setSelectionBehavior(QTableWidget.SelectRows)
        self.table.setEditTriggers(QTableWidget.NoEditTriggers)
        self.table.horizontalHeader().setStretchLastSection(True)

        layout.addLayout(toolbar)
        layout.addWidget(self.table)

        self.apply_styles()

    def apply_styles(self):
        self.setStyleSheet("""
            QWidget {
                background-color: white;
            }
            #primaryButton {
                background-color: #5352ed;
                color: white;
                border: none;
                padding: 8px 15px;
                border-radius: 4px;
            }
            #primaryButton:hover {
                background-color: #3742fa;
            }
            #secondaryButton {
                background-color: #dcdde1;
                border: none;
                padding: 8px 15px;
                border-radius: 4px;
            }
            #secondaryButton:hover {
                background-color: #c8c9cc;
            }
            QTableWidget {
                border: none;
                gridline-color: #f1f2f6;
            }
            QTableWidget::item {
                padding: 8px;
            }
            QTableWidget::item:selected {
                background-color: #5352ed22;
            }
            QHeaderView::section {
                background-color: #f8f9fa;
                padding: 8px;
                border: none;
                border-bottom: 2px solid #dcdde1;
            }
        """)

    def load_staffs(self):
        """加载员工列表"""
        self.table.setRowCount(0)
        sql = "SELECT * FROM users WHERE role = 'staff' ORDER BY id"
        staffs = db.fetch_all(sql)

        for row, staff in enumerate(staffs):
            self.table.insertRow(row)

            self.table.setItem(row, 0, QTableWidgetItem(str(staff["id"])))
            self.table.setItem(row, 1, QTableWidgetItem(staff["username"]))
            self.table.setItem(row, 2, QTableWidgetItem(staff["display_name"] or ""))
            self.table.setItem(row, 3, QTableWidgetItem("员工"))

            # 操作按钮
            btn_widget = QWidget()
            btn_layout = QHBoxLayout(btn_widget)
            btn_layout.setContentsMargins(0, 0, 0, 0)

            edit_btn = QPushButton("编辑")
            delete_btn = QPushButton("删除")
            reset_pwd_btn = QPushButton("重置密码")

            edit_btn.clicked.connect(lambda checked, s=dict(staff): self.edit_staff(s))
            delete_btn.clicked.connect(lambda checked, id=staff["id"]: self.delete_staff(id))
            reset_pwd_btn.clicked.connect(lambda checked, id=staff["id"]: self.reset_password(id))

            btn_layout.addWidget(edit_btn)
            btn_layout.addWidget(delete_btn)
            btn_layout.addWidget(reset_pwd_btn)

            self.table.setCellWidget(row, 4, btn_widget)

    def add_staff(self):
        """添加员工"""
        dialog = StaffDialog(self)
        if dialog.exec_() == QDialog.Accepted:
            self.load_staffs()

    def edit_staff(self, staff_data):
        """编辑员工"""
        dialog = StaffDialog(self, staff_data)
        if dialog.exec_() == QDialog.Accepted:
            self.load_staffs()

    def delete_staff(self, staff_id):
        """删除员工"""
        reply = QMessageBox.question(
            self, "确认删除",
            "确定要删除这个员工吗？此操作不可恢复！",
            QMessageBox.Yes | QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            try:
                sql = "DELETE FROM users WHERE id = ? AND role = 'staff'"
                db.execute(sql, (staff_id,))
                self.load_staffs()
            except Exception as e:
                QMessageBox.critical(self, "错误", f"删除失败：{str(e)}")

    def reset_password(self, staff_id):
        """重置密码"""
        reply = QMessageBox.question(
            self, "确认重置",
            "确定要重置该员工的密码吗？\n重置后的密码为：123456",
            QMessageBox.Yes | QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            try:
                default_password = hashlib.md5("123456".encode()).hexdigest()
                sql = "UPDATE users SET password = ? WHERE id = ?"
                db.execute(sql, (default_password, staff_id))
                QMessageBox.information(self, "成功", "密码已重置为：123456")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"重置失败：{str(e)}")
